package com.zhuzi.common.utils;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * &#064;Classname  DownFile
 *
 * @Version 1.0.0
 * &#064;Date  2022/2/23 9:02
 * &#064;Created  by yd
 */
public class DownFile {
    private static String getBrowser(HttpServletRequest request) {
        String UserAgent = request.getHeader("USER-AGENT").toLowerCase();
        if (UserAgent.contains("msie")) {
            return "IE";
        }
        if (UserAgent.contains("firefox")) {
            return "FF";
        }
        if (UserAgent.contains("safari")) {
            return "SF";
        }
        if (UserAgent.contains("mozilla")) {
            return "Chrome";
        }
        return null;
    }

    /**
     * 文件下载
     *
     * @param req      HttpServletRequest
     * @param response HttpServletResponse
     * @param paths    文件路径
     * @param fileName 下载显示的文件名
     */
    public static void downFile(HttpServletRequest req, HttpServletResponse response, Path paths, String fileName) {
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            String filenamedisplay = java.net.URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
            if ("FF".equals(getBrowser(req))) {
                // 针对火狐浏览器处理方式不一样了
                // filenamedisplay = new String(fileName.getBytes(StandardCharsets.UTF_8.name()), StandardCharsets.ISO_8859_1.name());
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + filenamedisplay);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");

            //设置传输的类型
            response.setHeader("Content-Type", "application/octet-stream");
            response.setHeader("Content-Transfer-Encoding", "chunked");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("application/OCTET-STREAM");

            if (Files.exists(paths)) {
                // JDK自带的;缓存是8192
                Files.copy(paths, out);
                // FileUtils.copyFile(paths.toFile(), outputStream);// 缓存是1024*4
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(out);
        }
    }

}
